﻿using CSRedis;
using God.ShoppingWebApi.DTO;
using God.ShoppingWebApi.DTO.User;
using God.ShoppingWebApi.Entities;
using God.ShoppingWebApi.IService;
using God.ShoppingWebApi.Properties;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace God.ShoppingWebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AdminUserLoginController : ControllerBase
    {
        private readonly IAdminLoginService _loginService;

        public AdminUserLoginController(IAdminLoginService loginService)
        {
            RedisHelper.Initialization(_client);
            _loginService = loginService;
        }
        private CSRedisClient _client = new CSRedisClient("127.0.0.1:6379,password=123456");

        [HttpGet]//验证码
        public IActionResult ValidateCode()
        {
            ValidateCodeHelper validateCodeHelper = new ValidateCodeHelper();
            string code = "";
            MemoryStream ms = validateCodeHelper.Create(out code);
            RedisHelper.Set("LoginValidateCode", code, 300);
            Response.Body.Dispose();

            return File(ms.ToArray(), @"image/png");
        }
        [HttpPost]//验证码
        public async Task<IActionResult> Yan(UserLoginDTO dTO)
         {
            string code = RedisHelper.Get("LoginValidateCode");

           
            if (string.IsNullOrEmpty(code))
            {
                return  Ok(  new { result = "图片验证过期", code = -2 });
            }
            if (code.ToLower().Equals(dTO.UserYan.ToLower()))
            {

               var token=await _loginService.GetUserTokenAsync(dTO);
               
                return Ok(token);
            }
            else
            {
                return  Ok(  new  { result = "验证失败", code = 0 });
            }
        }
    }
}
